package comJwt

import (
	"common/response"
	"context"
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"net/http"
)

type Auth struct {
	AccessSecret string
	AccessExpire int
}

// GetUser api 服务可以通过上下文获取user
func GetUser(ctx context.Context) (*UserStdClaims, error) {
	user := ctx.Value("token")
	if claims, ok := user.(*UserStdClaims); ok {
		return claims, nil
	} else {
		return nil, errors.New("获取user失败")
	}
}
func DefatHandle(w http.ResponseWriter, r *http.Request, next http.HandlerFunc, Config Auth) {
	authorization := r.Header.Get("authorization")
	if authorization == "" {
		w.WriteHeader(401)
		response.Response(w, nil, errors.New("请登陆"))
		return
	}
	token, err := jwt.ParseWithClaims(authorization, &UserStdClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(Config.AccessSecret), nil
	})

	if err != nil {
		w.WriteHeader(401)
		response.Response(w, nil, err)
		return
	}
	if !token.Valid {
		w.WriteHeader(401)
		response.Response(w, nil, errors.New("invalid token"))
		return
	}

	claims, ok := token.Claims.(*UserStdClaims)
	if !ok {
		w.WriteHeader(401)
		response.Response(w, nil, errors.New("invalid claims"))
		return
	}
	fmt.Println(claims)
	ctx := context.WithValue(r.Context(), "token", claims)
	next(w, r.WithContext(ctx))
}
